<?php

namespace magein\think\utils\api;

use magein\think\utils\service\BaseService;
use think\db\exception\DbException;
use think\Paginator;

class ApiBaseService extends BaseService
{

    /**
     * @return array
     */
    protected function search(): array
    {
        return [];
    }

    /**
     * @param int|null $page_size
     * @return array|Paginator|null
     * @throws DbException
     */
    public function paginate(int $page_size = null)
    {
        $search = $this->search();
        $where = [];
        if ($search) {
            foreach ($search as $item) {
                if (!is_array($item)) {
                    $value = request()->param($item, '');
                    if ($value === '') {
                        continue;
                    }
                    $where[] = [$item, '=', $value];
                } else {
                    $where[] = $item;
                }
            }
        }

        $model = parent::getModel();

        $model = $model->with($this->with())->where($where)->field($this->fields);

        $data = $model->paginate(ApiPaginate::config());

        return ApiPaginate::api($data);
    }


    /**
     * 允许新增的字段
     * @return array
     */
    protected function allowCreateField()
    {
        return [];
    }

    /**
     * 允许更新的字段
     * @return array
     */
    protected function allowUpdateField()
    {
        return $this->allowCreateField();
    }

    /**
     * 创建
     * @param $data
     * @return \magein\utils\Result|\think\model\contract\Modelable
     */
    public function create($data = [])
    {
        if (empty($data)) {
            $data = request()->only($this->allowCreateField());
        }

        return parent::create($data);
    }

    /**
     * @param $data
     * @return bool|\magein\utils\Result
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function update($data = [])
    {
        if (empty($data)) {
            $data = request()->only($this->allowUpdateField());
        }

        $data['id'] = request()->param('id');

        return parent::update($data);
    }
}